using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

[System.Serializable]
public class UI_TreeConnectionDetails
{
    public UI_TreeConnectionHandler childNode;
    public NodeDirectionType direction;

    [Range(100f, 350f)] public float length;
    [Range(-50, 50)] public float rotateOffset;
}
public class UI_TreeConnectionHandler : MonoBehaviour
{
    [SerializeField] private UI_TreeConnectionDetails[] details;
    [SerializeField] private UI_TreeConnection[] connections;
    public RectTransform rect => GetComponent<RectTransform>();

    private Image connectionImage;
    private Color originalColor;
    private void Awake()
    {
        if (connectionImage != null)
        {
            originalColor = connectionImage.color;
        }
    }
    private void OnValidate()
    {
        if (details.Length != connections.Length)
            return;
        UpdateConnections();
    }

    public UI_TreeNode[] GetAllChildNodes()
    {
        List<UI_TreeNode> treeNodes = new();
        foreach (var node in details)
        {
            if (node.childNode == null)
                continue;
            treeNodes.Add(node.childNode.GetComponent<UI_TreeNode>());
        }
        return treeNodes.ToArray();
    }
    //更新连接
    private void UpdateConnections()
    {
        for (int i = 0; i < details.Length; i++)
        {
            var detail = details[i];
            var connection = connections[i];
            //更新分支的旋转和长度
            connection.DirectConnection(detail.direction, detail.length, detail.rotateOffset);
            //获得连接点
            Vector2 position = connection.GetConnectionPoint(rect);
            //得到当前节点的连接线
            Image connectionImage = connection.GetConnectionImage();

            if (detail.childNode == null)
                continue;
            //更新子节点的位置
            detail.childNode.SetPosition(position);
            //设置子节点连接线的Image
            detail.childNode.SetConnectionImage(connectionImage);
            //detail.childNode 这个 Transform 节点设置为其父物体的最后一个子物体。
            detail.childNode.transform.SetAsLastSibling();
        }
    }
    public void UpdateAllConnection()
    {
        //更新当前节点
        UpdateConnections();
        //更新当前节点的子节点
        foreach (var detail in details)
        {
            if (detail.childNode == null) continue;
            detail.childNode.UpdateAllConnection();
        }
    }
    public void SetPosition(Vector2 position) => rect.anchoredPosition = position;

    public void UnlockConnectionImageColor(bool isUnlocked)
    {
        if (connectionImage == null)
            return;
        connectionImage.color = isUnlocked ? Color.white : originalColor;
    }
    public void SetConnectionImage(Image image) => connectionImage = image;
}
